import React, { useRef, forwardRef, useImperativeHandle, useEffect, useState } from 'react';
import { Drawer, Form, Button, Tabs, FormInstanceFunctions } from 'tdesign-react';
import { FormField } from 'types/Form.d';
import { useSingleMessage } from 'composables/useMessage';
import { throttle } from 'utils/index';
import IppeakTable from '../IppeakTable';
import DrawerForm from '../DrawerForm';
import './index.module.less';

interface TableConfig {
  dataSource: any[];
  columns: any[];
  rowKey: string;
  loading: boolean;
  pagination: any;
  selectedRowKeys?: (string | number)[];
  onSelectChange?: (value: (string | number)[]) => void;
  scroll?: any;
  tableHeight?: string | number;
}

interface RichEditorConfig {
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  height?: number;
}

interface SakuraDrawerProps {
  visible: boolean;
  onClose: () => void;
  title: string;
  type: 'Add' | 'Edit';
  initialValues?: any;
  width?: string;
  size?: 'small' | 'medium' | 'large';
  placement?: 'left' | 'right' | 'top' | 'bottom';
  destroyOnClose?: boolean;
  showCloseBtn?: boolean;
  showConfirmBtn?: boolean;
  confirmText?: string;
  cancelText?: string;
  onConfirm?: (type: string, values: any, cb: () => void) => void;
  onCancel?: () => void;
  formFields?: FormField[];
  drawerFormFields?: any[]; // 新增：DrawerForm字段配置
  uploadApi?: (formData: FormData) => Promise<any>; // 新增：上传接口
  tableConfig?: TableConfig;
  richEditorConfig?: RichEditorConfig;
  tabs?: Array<{
    label: string;
    value: string;
    content: React.ReactNode;
  }>;
  children?: React.ReactNode;
  footer?: React.ReactNode;
  header?: React.ReactNode;
}

const { FormItem } = Form;
const { TabPanel } = Tabs;

const SakuraDrawer = forwardRef<any, SakuraDrawerProps>(
  (
    {
      visible,
      onClose,
      title,
      type,
      initialValues = {},
      width = '800px',
      size = 'large',
      placement = 'right',
      destroyOnClose = true,
      showCloseBtn = true,
      showConfirmBtn = true,
      confirmText = '确定',
      cancelText = '取消',
      onConfirm,
      onCancel,
      formFields = [],
      drawerFormFields = [],
      uploadApi,
      tableConfig,
      richEditorConfig,
      tabs,
      children,
      footer,
      header,
    },
    ref
  ) => {
    const { showMessage } = useSingleMessage();
    const [form] = Form.useForm();
    const formRef = useRef<FormInstanceFunctions>();
    const [activeTab, setActiveTab] = useState('form');
    const [richEditorValue, setRichEditorValue] = useState(richEditorConfig?.value || '');
    const [uploadedImageUrl, setUploadedImageUrl] = useState<string>('');
    const [uploads,setUploads] = useState([])
    const [uploadedImageUrls, setUploadedImageUrls] = useState<Record<string, string>>({});
    const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
    const [formValues, setFormValues] = useState<any>({});
    const renderRichEditor = () => {
      return (
        <div className="rich-editor-container">
          <div
            contentEditable
            className="rich-editor"
            style={{ 
              minHeight: richEditorConfig?.height || 300,
              border: '1px solid #dcdcdc',
              borderRadius: '4px',
              padding: '12px',
              outline: 'none'
            }}
            dangerouslySetInnerHTML={{ __html: richEditorValue }}
                         onInput={(e) => {
               const value = e.currentTarget.innerHTML;
               setRichEditorValue(value);
               richEditorConfig?.onChange?.(value);
             }}
          />
        </div>
      );
    };

    const initForm = () => {
      // 清除所有校验状态，避免打开时显示校验错误
      form.clearValidate();
      form.reset();
      
      const processedInitialValues = initialValues ? { ...initialValues } : {};
      if (Array.isArray(drawerFormFields) && drawerFormFields.length > 0) {
        drawerFormFields.forEach((field: any) => {
          const fieldName = field?.name;
          if (!fieldName) return;
          const isUnset = processedInitialValues[fieldName] === undefined || processedInitialValues[fieldName] === null;
          if (isUnset && field?.defaultValue !== undefined) {
            processedInitialValues[fieldName] = field.defaultValue;
          }
        });
      }
      
      // 处理所有图片字段的回显，包括cover、banner_image、en_banner_image等
      const imageFields = ['cover', 'banner_image', 'en_banner_image', 'logo', 'image'];
      imageFields.forEach(fieldName => {
        if (initialValues && initialValues[fieldName] && typeof initialValues[fieldName] === 'string' && initialValues[fieldName].trim() !== '') {
          processedInitialValues[fieldName] = [{
            url: initialValues[fieldName],
            name: '',
            status: 'success'
          }];
        } else {
          // 添加模式或没有图片时，设置为空数组
          processedInitialValues[fieldName] = [];
        }
      });
      
      // 使用 setTimeout 确保在下一个事件循环中设置值，避免触发校验
      setTimeout(() => {
        form.setFieldsValue(processedInitialValues);
        setRichEditorValue(richEditorConfig?.value || '');
     
        // 如果有配图URL，也设置到uploadedImageUrl状态中
        if (initialValues && initialValues.cover && typeof initialValues.cover === 'string' && initialValues.cover.trim() !== '') {
          setUploadedImageUrl(initialValues.cover);
        } else {
          // 添加模式时清空uploadedImageUrl
          setUploadedImageUrl('');
        }
        
        // 处理多个图片字段的URL状态
        const imageUrls: Record<string, string> = {};
        imageFields.forEach(fieldName => {
          if (initialValues && initialValues[fieldName] && typeof initialValues[fieldName] === 'string' && initialValues[fieldName].trim() !== '') {
            imageUrls[fieldName] = initialValues[fieldName];
          }
        });
        setUploadedImageUrls(imageUrls);
      }, 0);
    };

    const handleSubmit = throttle(async () => {
      try {
        // 先清除之前的校验状态，然后进行新的校验
        form.clearValidate();
        // 验证表单
        await form.validate();
        
        const formValues = form.getFieldsValue(true);
        const allValues = {
          ...formValues,
          ...(richEditorConfig && { richContent: richEditorValue }),
        };
        
        // 检查必填字段（只对visible为true的字段进行校验）
        const requiredFields = drawerFormFields.filter(field => {
          if (!field.required) return false;
          // 如果字段有visible函数，需要检查当前表单值下是否应该显示
          if (field.visible && typeof field.visible === 'function') {
            return field.visible(allValues);
          }
          // 如果没有visible函数，默认需要校验
          return true;
        });
        
        const isEmptyValue = (val: any) => {
          if (val === undefined || val === null) return true;
          if (typeof val === 'string') return val.trim() === '';
          if (Array.isArray(val)) return val.length === 0;
          return false;
        };
        
        const missingFields = requiredFields.filter(field => {
          const value = (allValues as any)[field.name];
          return isEmptyValue(value);
        });
        
        if (missingFields.length > 0) {
          const fieldNames = missingFields.map(field => field.label).join('、');
          showMessage('error', `请完善数据后重试`);
          return;
        }
        
        if (onConfirm) {
          setConfirmLoading(true);
          const stopLoadingAndReset = () => {
            try {
              initForm();
            } finally {
              setConfirmLoading(false);
            }
          };
          const maybePromise = onConfirm(type, allValues, stopLoadingAndReset);
          // 若返回 Promise，则在完成后关闭 loading（防止未调用回调的情况）
          if ((maybePromise as any)?.finally) {
            (maybePromise as any).finally(() => setConfirmLoading(false));
          }
        }
      } catch (err) {
        console.error('表单验证失败:', err);
        showMessage('error', '请完善数据后重试');
      }
    }, 1000);

    const handleCancel = () => {
      if (onCancel) {
        onCancel();
      } else {
        onClose();
      }
      setConfirmLoading(false);
    };

    useEffect(() => {
      if (visible) {
        initForm();
      }
    }, [visible]);

    useImperativeHandle(ref, () => ({
      form,
      getForm: () => form,
      setFieldValue: (name: string, value: any) => {
        form.setFieldsValue({ [name]: value });
      },
      getFieldValue: (name: string) => {
        return form.getFieldValue(name);
      },
      getFieldsValue: () => {
        return form.getFieldsValue(true);
      },
      validate: () => {
        return form.validate();
      },
      reset: () => {
        form.reset();
        setRichEditorValue('');
        setUploadedImageUrl('');
        setUploadedImageUrls({});
      },
      setRichEditorValue: (value: string) => {
        setRichEditorValue(value);
      },
      getUploadedImageUrl: () => {
        return uploadedImageUrl;
      },
      // 新增：获取所有上传字段的值（后端返回的路径）
      getUploadedImageUrls: () => {
        return uploadedImageUrls;
      },
    }));

    const renderContent = () => {
      if (tabs && tabs.length > 0) {
        return (
          <Tabs value={activeTab} onChange={(value) => setActiveTab(value as string)}>
            {tabs.map((tab) => (
              <TabPanel key={tab.value} value={tab.value} label={tab.label}>
                {tab.content}
              </TabPanel>
            ))}
          </Tabs>
        );
      }

      if (children) {
        return children;
      }

      return (
        <div className="sakura-drawer-content">
          {drawerFormFields.length > 0 && (
            <div className="form-section">
              <DrawerForm
                fields={drawerFormFields}
                form={form}
                formRef={formRef as any}
                labelWidth={90}
                inputWidth="100%"
                minInputWidth="150px"
                uploadApi={uploadApi}
                onFieldChange={(name: string, value: any) => {
                  // 触发组件重新渲染以更新字段可见性
                  setFormValues((prevValues: any) => ({
                    ...prevValues,
                    [name]: value
                  }));
                }}
                onUploadSuccess={(url: string, fieldName: string) => {
                  setUploadedImageUrl(url);
                  setUploadedImageUrls(prev => ({
                    ...prev,
                    [fieldName]: url
                  }));
                }}
              />
            </div>
          )}

          {tableConfig && (
            <div className="table-section">
              <IppeakTable
                dataSource={tableConfig.dataSource}
                columns={tableConfig.columns}
                rowKey={tableConfig.rowKey}
                loading={tableConfig.loading}
                pagination={tableConfig.pagination}
                selectedRowKeys={tableConfig.selectedRowKeys}
                onSelectChange={tableConfig.onSelectChange}
                scroll={tableConfig.scroll}
                tableHeight={tableConfig.tableHeight}
              />
            </div>
          )}

          {richEditorConfig && (
            <div className="rich-editor-section">
              {renderRichEditor()}
            </div>
          )}
        </div>
      );
    };

    const renderFooter = () => {
      if (footer) {
        return footer;
      }

      if (!showConfirmBtn && !showCloseBtn) {
        return null;
      }

      return (
        <div className="sakura-drawer-footer">
          {showCloseBtn && (
            <Button theme="default" onClick={handleCancel}>
              {cancelText}
            </Button>
          )}
          {showConfirmBtn && (
            <Button theme="primary" loading={confirmLoading} disabled={confirmLoading} onClick={handleSubmit}>
              {confirmText}
            </Button>
          )}
        </div>
      );
    };

    const drawerTitle = type === 'Add' ? `新增${title}` : `编辑${title}`;

          return (
       <Drawer
         visible={visible}
         onClose={onClose}
         header={header || drawerTitle}
         size={size}
         placement={placement}
         destroyOnClose={destroyOnClose}
         closeOnOverlayClick={false}
         footer={renderFooter()}
         className="sakura-drawer-wrapper"
         style={{ '--drawer-width': width } as React.CSSProperties}
       >
         {renderContent()}
       </Drawer>
      );
  }
);

SakuraDrawer.displayName = 'SakuraDrawer';

export default SakuraDrawer;
